import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

/**
 * 同步引入方式，无法实现路由懒加载
import Login from '@/views/Login'
import Layout from '@/views/Layout'
import Home from '@/views/Home'
import Category from '@/views/Category'
import Cart from '@/views/Cart'
import My from '@/views/My'
import GoodsDetail from '@/views/GoodsDetail'
import Order from '@/views/Order'
import NotFound from '@/views/NotFound'
*/

// 动态引入组件的方式，实现路由懒加载
const Login = () => import('@/views/Login')
const Layout = () => import('@/views/Layout')
const Home = () => import('@/views/Home')
const Category = () => import('@/views/Category')
const Cart = () => import('@/views/Cart')
const My = () => import('@/views/My')
const GoodsDetail = () => import('@/views/GoodsDetail')
const Order = () => import('@/views/Order')
const NotFound = () => import('@/views/NotFound')

NProgress.configure({ showSpinner: false })

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'Login', // 命名路由，就是给路由取个名字（跳转的时候，可以根据名字跳）
    component: Login,
    meta: {
      title: '登录'
    }
  },
  {
    path: '/detail',
    component: GoodsDetail,
    meta: {
      title: '商品详情'
    }
  },
  {
    path: '/order',
    component: Order,
    meta: {
      isNeedLogin: true,
      title: '订单'
    }
  },
  // {
  //   // 动态路径参数
  //   path: '/detail/:proid',
  //   component: GoodsDetail
  // },
  {
    path: '/',
    name: 'Layout',
    component: Layout,
    redirect: '/home',
    children: [
      //  嵌套路由规则前面不要加 /
      {
        path: 'home',
        component: Home,
        meta: {
          title: '首页'
        }
      },
      {
        path: 'category',
        component: Category,
        meta: {
          title: '分类'
        }
      },
      {
        path: 'cart',
        component: Cart,
        meta: {
          title: '购物车'
        }
      },
      {
        path: 'my',
        component: My,
        meta: {
          isNeedLogin: true,
          title: '我的'
        }
      }
    ]
  },
  {
    path: '*',
    component: NotFound
  }
  // {
  //   path: '/about',
  //   name: 'about',
  //   // route level code-splitting
  //   // this generates a separate chunk (about.[hash].js) for this route
  //   // which is lazy-loaded when the route is visited.
  //   // 路由懒加载
  //   component: () =>
  //     import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
  // }
]

const router = new VueRouter({
  // mode: 'history', // 模式（hash、history）
  // base: process.env.BASE_URL,
  routes
})

const originPush = VueRouter.prototype.push
// 覆盖原型链的push
VueRouter.prototype.push = function (location, resolve, reject) {
  // this:路由实例对象

  // 判断用户有没有传后面两个可选参数
  if (resolve || reject) {
    return originPush.call(this, location, resolve, reject)
  } else {
    // 用户只传了第一个参数
    /*
      默认底层： catch()方法代码  throw err : 抛出异常
      吞掉报错原理： 重写catch()方法,把默认底层的 throw err给去掉，就不会抛出异常
      */
    return originPush.call(this, location).catch(err => {
      console.log(err)
    })
  }
}

/**
 * from：施主从何而来？
 * to：施主要到哪里去？
 * next：控制下一步往哪走？以及能否走
 */
router.beforeEach((to, from, next) => {
  NProgress.start()
  /**
   * 判断去的页面是否是需要先进行登录的（my、order），如果是，则判断是否有token，如果有则放行，没有则跳转到登录页
   * 如果发现去的页面，压根不用判断是否登录（不需要权限）则直接放行
   */
  // if (to.path === '/my' || to.path === '/order') {
  if (to.meta.isNeedLogin) {
    // 判断是否有token
    if (store.state.user.token) {
      // 有值
      next()
    } else {
      // 没有值
      next('/login')
    }
  } else {
    next()
  }
})

/**
 * 已经进入到某个路由了
 */
router.afterEach((to, from) => {
  NProgress.done()
  document.title = to.meta.title
})

export default router
